package cn.yunbamboos.mybatis.mapping.methods.query;

import cn.yunbamboos.mybatis.mapping.methods.BaseQueryMethod;
import cn.yunbamboos.mybatis.metadata.TableInfo;
import org.apache.ibatis.session.Configuration;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("DuplicatedCode")
public class QueryByPrimaryKey extends BaseQueryMethod {

    public QueryByPrimaryKey(Configuration configuration, TableInfo tableInfo) {
        this("queryByPrimaryKey", configuration, tableInfo);
    }

    public QueryByPrimaryKey(String methodName, Configuration configuration, TableInfo tableInfo) {
        super(methodName, configuration, tableInfo);
    }

    @Override
    public String getSQL() {
        List<String> columns = new ArrayList<>();
        List<String> wheres = new ArrayList<>();
        this.tableInfo.getPrimaryKeyList().forEach(pk -> {
            columns.add(BACKTICK + pk.getColumn() + BACKTICK);
            if (wheres.isEmpty()) {
                wheres.add(BACKTICK + pk.getColumn() + BACKTICK + SPACE + EQUALS + SPACE + HASH_LEFT_BRACE + pk.getColumn() + RIGHT_BRACE);
            }
        });
        this.tableInfo.getFieldList().forEach(field -> {
            columns.add(BACKTICK + field.getColumn() + BACKTICK);
        });
        return SELET_WHERE(columns, BACKTICK + this.tableInfo.getTableName() + BACKTICK, wheres);
    }

}